package playnsimple.core.graphics;

import static playn.core.PlayN.graphics;

import java.util.ArrayList;

import playn.core.CanvasImage;
import playn.core.ImageLayer;

import com.google.common.collect.Lists;

public class ImageStack {
    
    private ArrayList<CanvasImage> imageList = Lists.newArrayList();
    private CanvasImage image;

    public ImageStack(CanvasImage rootImage) {
        imageList.add(rootImage);
        image = rootImage;
    }

    public void addToBottom(CanvasImage newImage, int margin) {
        imageList.add(image);
        ArrayList<CanvasImage> images = Lists.newArrayList(this.image, newImage);
        
        // generate new image
        Float imageWidth = getImageWidth(images);
        Float imageHeight = this.image.height() + newImage.height() + margin;        
        CanvasImage rootImage = graphics().createImage(imageWidth, imageHeight);
        
        // update object image
        float x = (rootImage.width() - this.image.width()) * 0.5f;
        float y = 0;
        rootImage.canvas().drawImage(this.image, x, y);
        
        // add new image
        x = (rootImage.width() - newImage.width()) * 0.5f;
        y = imageHeight - newImage.height();
        rootImage.canvas().drawImage(newImage, x, y);
        
        this.image = rootImage;
    }
    
    private static Float getImageWidth(ArrayList<CanvasImage> imageList) {
        Float maxWidth = 0f;
        Float imageWidth = 0f;
        for (CanvasImage image : imageList) {
            imageWidth = image.width();
            if ( imageWidth > maxWidth ) {
                maxWidth = imageWidth;
            }
        }
        return maxWidth;
    }
    
    public float width() {
        return this.image.width();
    }
    
    public float height() {
        return this.image.height();
    }

    public ImageLayer layer() {
        return graphics().createImageLayer(this.image);
    }
}
